/**
 *  Copyright 2011 Marco Berri - marcoberri@gmail.com
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License.
 **/
package com.stats.view;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.utils.Default;
import com.utils.StringUtil;

/**
 *
 * @author Marco Berri marcoberri@gmail.com
 */
public class Log extends com.stats.Base {

    /**
     * tipologia di tabella view|save
     */
    protected String table = "view";

    /**
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        
        super.processRequest(request,response);

        /*  FIXME
        //prelevo i parametri in arrivo che devono essere 1... per ora...
        String key = request.getParameter("key");
        if (StringUtil.isNullOrEmpty(key) || (!key.equals(conf.getStats_key()))) {
        fatal("key is null or wrong!");
        return;
        }
         */
        table = Default.toString(request.getParameter("table"), table);
        HashMap<String, HashMap<String, String>> cache_map = new HashMap<String, HashMap<String, String>>();

        //statistiche di visualizzazione
        ArrayList list = new ArrayList();

        try {
            Statement stat = this.conn_stats.createStatement();
            Statement db = this.conn_url.createStatement();

            ResultSet rsstats;
            rsstats = stat.executeQuery("select * from " + table + " order by ts desc limit 100");


            while (rsstats.next()) {
                HashMap<String, Object> m = new HashMap<String, Object>();

                if (!StringUtil.isNullOrEmpty(rsstats.getString("header"))) {

                    HashMap<String, String> header_map = new HashMap<String, String>();

                    try {
                        String[] h_string = rsstats.getString("header").split("\\|\\|");

                        if (h_string == null || h_string.length <= 0) {
                            continue;
                        }

                        for (String s : h_string) {
                            String k_v[] = s.split("\\|");
                            if(k_v == null || k_v.length < 1)
                                continue;

                            if(!isValidHeaderKey(k_v[0]))
                                continue;
                            
                            try {
                                header_map.put(k_v[0], k_v[1]);
                            } catch (Exception ex) {
                                //debug("Exception", ex);
                                continue;
                            }
                        }
                    } catch (Exception e) {
                        // continue;
                        fatal("Exception", e);
                    }

                    //smazzo la header
                    m.put("header", header_map);
                }

                m.put("ts", rsstats.getString("ts"));
                m.put("ip", rsstats.getString("ip"));
                m.put("fk_url_id", rsstats.getString("fk_url_id"));

                if (cache_map.get(rsstats.getString("fk_url_id")) == null) {

                    //carico anche i dati di riferimento dell'ip originale da db originale
                    ResultSet rsdb = db.executeQuery("select * from url where id ='" + rsstats.getString("fk_url_id") + "'");

                    while (rsdb.next()) {
                        m.put("url", rsdb.getString("url"));
                        m.put("t", rsdb.getString("t"));
                        m.put("t_end", rsdb.getString("t_end"));

                        HashMap<String, String> t = new HashMap<String, String>();
                        t.put("url", rsdb.getString("url"));
                        t.put("t", rsdb.getString("t"));
                        t.put("t_end", rsdb.getString("t_end"));

                        cache_map.put(rsstats.getString("fk_url_id"), t);
                    }

                    rsdb.close();
                } else {
                    HashMap<String, String> temp_map = (HashMap<String, String>) cache_map.get(rsstats.getString("fk_url_id"));
                    m.put("url", temp_map.get("url"));
                    m.put("t", temp_map.get("t"));
                    m.put("t_end", temp_map.get("t_end"));
                }

                list.add(m);
            }

            rsstats.close();


        } catch (SQLException ex) {
            fatal("SQLException", ex);
        }



        response.setContentType("text/html;charset=" + this.conf.getUrl().getCharset());

        PrintWriter out = response.getWriter();
        HashMap<String, Object> data = new HashMap<String, Object>(2);
        data.put("stats", list);
        data.put("table", table);
        data.put("tot_view", tot_view);
        data.put("tot_save", tot_save);
        data.put("tot_ts", tot_ts);
        out.println(velocity.render("template/stats/log.vtl", data));
        out.close();


    }

    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Statistiche di click sullo short url";
    }// </editor-fold>

    /**
     *
     * @param config
     * @throws ServletException
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);

    }

    /**
     * Destroy
     */
    @Override
    public void destroy() {
        super.destroy();
    }
}
